package com.example.springsecuritywithdatabase.controller;

import com.example.springsecuritywithdatabase.bean.UserInfo;
import com.example.springsecuritywithdatabase.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class HelloController {
    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/get-user")
    public UserInfo getUser(@RequestParam String username) {
        return userInfoService.getUserInfoByUsername(username);
    }

    @PreAuthorize("hasAnyRole('user')") // 只能user角色才能访问该方法
    @GetMapping("/user")
    public String user() {
        return "user你好";
    }

    @PreAuthorize("hasAnyRole('admin')") // 只能admin角色才能访问该方法
    @GetMapping("/admin")
    public String admin() {
        return "admin你好";
    }

    @PreAuthorize("hasAnyRole('user')") // 只能admin角色才能访问该方法
    @GetMapping("/user3")
    public String user3() {
        return "user3你好";
    }
    /*@PostMapping("/add-user")
    public int addUser(@RequestBody UserInfo userInfo) {
        return userInfoService.insertUser(userInfo);
    }*/

    @PostMapping("/add-user")
    public int addUser(@RequestParam("username") String username,@RequestParam("password") String password,@RequestParam("role") String role) {
        UserInfo u=new UserInfo();
        u.setUsername(username);
        u.setPassword(password);
        u.setRole(role);
        System.out.println(u);
        return userInfoService.insertUser(u);
    }

    @GetMapping("/add-user")
    public ModelAndView addUser(ModelAndView modelAndView) {
        modelAndView.setViewName("addUser");
        return modelAndView;
    }
}